//
//  APPCache.swift
//  Lease_IOS
//
//  Created by Mr.wang on 2018/12/20.
//  Copyright © 2018 Mr.wang. All rights reserved.
//

import TMCache
import HandyJSON

class AppCache: TMCache {
    static let shared: AppCache = AppCache.shared()
}

extension HandyJSON {
    static var describing: String {
        return String(describing: self).md5()
    }
}

extension AppCache {
    
    func cacheObject<T: HandyJSON>(object: T) {
        guard let jsonString = object.toJSONString() else {
            return
        }
        AppCache.shared.setObject(jsonString as NSCoding, forKey: T.describing)
    }
    
    func object<T: HandyJSON>(for kind: T.Type) -> T {
        guard let jsonString = AppCache.shared.object(forKey: T.describing) as? String,
        let object = T.deserialize(from: jsonString) else {
            return T()
        }
        return object
    }
    
    func updateObject<T: HandyJSON>(for kind: T.Type, closure: (inout T) -> ()) {
        var object = self.object(for: kind)
        closure(&object)
        self.cacheObject(object: object)
    }
    
    func removeObject<T: HandyJSON>(for kind: T.Type) {
        AppCache.shared.removeObject(forKey: T.describing)
    }
    
}
